//
//  CZEmoticonToolBar.swift
//  Blog
//
//  Created by whitcast on 16/7/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//  CZEmoticonToolBar按钮的枚举类型
enum CZEmoticonToolBarButtonType: Int {
    // 默认
    case Normal = 0
    // Emoji
    case Emoji = 1
    // 浪小花
    case Lxh = 2
}

class CZEmoticonToolBar: UIStackView {
    // 记录上次选中按钮
    var lastSelectedButton: UIButton?
    //  定义选中toolbar按钮的闭包
    var selectedToolBarButtonClosure: ((type: CZEmoticonToolBarButtonType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 添加控件设置布局方式
    private func setupUI() {
        // 设置布局 水平布局
        axis = .Horizontal
        // 设置子控件填充方式,平均分配
        distribution = .FillEqually
        
        addChildButton("默认", imageName: "compose_emotion_table_left",type: .Normal)
        addChildButton("Emoji", imageName: "compose_emotion_table_mid",type: .Emoji)
        addChildButton("浪小花", imageName: "compose_emotion_table_right",type: .Lxh)

    }
    
    
    
    private func addChildButton(title: String, imageName: String, type: CZEmoticonToolBarButtonType) {
        let button = UIButton()
        
        // 设置tag值，把枚举的原始作为tag
        button.tag = type.rawValue
        // 添加事件
        button.addTarget(self, action: "buttonAction：", forControlEvents: .TouchUpInside)
        // 设置文字及颜色
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        // 设置背景图片
        button.setBackgroundImage(UIImage(named: imageName + "_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: imageName + "_selected"), forState: .Selected)
        // 取消高亮
        button.adjustsImageWhenHighlighted = false
        
        addArrangedSubview(button)
    }
    // MARK: -- 点击事件
    @objc private func buttonAction(button: UIButton) {
        // 判断是否是同一个按钮
        if lastSelectedButton == button {
            return
        }
        
        lastSelectedButton?.selected = false
        button.selected = true
        lastSelectedButton = button
        
        // 通过tag获取枚举成员
        let type = CZEmoticonToolBarButtonType(rawValue: button.tag)!
        // 执行闭包回调
        selectedToolBarButtonClosure?(type: type)
    }

}
